package com.csoa.community.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.csoa.community.R;
import com.csoa.community.adapter.EmailAdapter;
import com.csoa.community.adapter.GalleryAdapter;
import com.csoa.community.adapter.ViewPagerAdapter;
import com.csoa.community.bean.EmailBean;
import com.csoa.community.net.WcfAsyncTask;
import com.csoa.community.requests.AbstractRequest;
import com.csoa.community.requests.EmailListRequest;
import com.csoa.community.singletons.GlobalVars;
import com.csoa.community.utils.StringUtils;
import com.csoa.community.widget.PullToRefreshBase.OnRefreshListener;
import com.csoa.community.widget.NarView;
import com.csoa.community.widget.PullToRefreshListView;

public class EmailActivity extends BaseActivity {

	private ArrayList<View> mViewList;
	private ViewPagerAdapter mAdapter;
	private ViewPager mViewPager;
	private Gallery mGallery;
	private GalleryAdapter mEmailAdapter;
	private PullToRefreshListView mToBeReadPullListView;
	private ListView mToBeReadListView;

	private PullToRefreshListView mHaveReadPullListView;
	private ListView mHaveReadListView;

	public static List<EmailBean> mToBeReadEmails = new ArrayList<EmailBean>();
	public static List<EmailBean> mHaveReadEmails = new ArrayList<EmailBean>();
	private EmailAdapter mToBeReadAdapter;
	private EmailAdapter mHaveReadAdapter;
	private View mViewToBeRead;
	private View mViewHaveRead;
	private boolean[] mIsLoad = new boolean[] { false, false };
	protected int currentToBeReadPage = 1;
	protected int currentHaveReadPage = 1;
	ProgressBar mProgressToBeRead;
	ProgressBar mProgressHaveRead;
	private NarView narView;
//	protected boolean isPullRefreshHaveRead = false;
//	protected boolean isPullRefreshToBeRead = false;

	@Override
	public void initData() {

		mToBeReadEmails.clear();
		mHaveReadEmails.clear();
		
		mToBeReadAdapter = new EmailAdapter(EmailActivity.this,
				mToBeReadEmails);
		mToBeReadListView.setAdapter(mToBeReadAdapter);
		buildRequestToBeRead(GlobalVars.currentUser.loginName,
				currentToBeReadPage, true);
		mToBeReadPullListView.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				if(mToBeReadPullListView.hasPullFromTop()) {
//					isPullRefreshToBeRead = true;
					currentToBeReadPage = 1;
					buildRequestToBeRead(GlobalVars.currentUser.loginName,
							currentToBeReadPage, true);
				}else {
//					isPullRefreshToBeRead = false;
					buildRequestToBeRead(GlobalVars.currentUser.loginName,
							currentToBeReadPage, false);
				}
				
			}
		});
		mToBeReadListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				EmailBean emailBean = mToBeReadEmails
						.get(position);
				startActivity(position,emailBean,false,GlobalVars.TO_BE_READ);
//				buildRequestMeeting(emailBean.ID, emailBean.RID,
//						GlobalVars.ISSUED, false,
//						GlobalVars.READ_TYPE_TO_BE_READ, GlobalVars.TO_BE_READ);
			}
		});

		mHaveReadAdapter = new EmailAdapter(EmailActivity.this,
				mHaveReadEmails);
		mHaveReadListView.setAdapter(mHaveReadAdapter);
		mHaveReadPullListView.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				if(mHaveReadPullListView.hasPullFromTop()) {
//					isPullRefreshHaveRead  = true;
					currentHaveReadPage = 1;
					buildRequestHaveRead(GlobalVars.currentUser.loginName,
							currentHaveReadPage, true);

				}else {
//					isPullRefreshHaveRead  = false;
					buildRequestHaveRead(GlobalVars.currentUser.loginName,
							currentHaveReadPage, false);
					
				}
			}
		});

		mHaveReadListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				EmailBean emailBean = mHaveReadEmails
						.get(position);
				startActivity(position,emailBean,true,GlobalVars.HAVE_READ);
//				buildRequestMeeting(offDocDetail.ID, offDocDetail.RID,
//						GlobalVars.ISUPDATE, false,
//						GlobalVars.READ_TYPE_HAVE_READ, GlobalVars.HAVE_READ);
			}
		});

	}

	private void initCenterUI(boolean isShowList,ListView list,ProgressBar progress) {
		if (isShowList) {
			if (list.getVisibility() != View.VISIBLE) {
				list.setVisibility(View.VISIBLE);
			}
			if (progress.getVisibility() != View.INVISIBLE) {
				progress.setVisibility(View.INVISIBLE);
			}
		} else {
			if (progress.getVisibility() != View.INVISIBLE) {
				progress.setVisibility(View.INVISIBLE);
			}
			if (progress.getVisibility() != View.VISIBLE) {
				progress.setVisibility(View.VISIBLE);
			}
		}
	}

	/**
	 * 
	 * @param position 
	 * @param ID
	 */
	protected void startActivity(int position, EmailBean emailBean,boolean isRead,int requestCode) {
		Intent intent = new Intent(EmailActivity.this,
				EmailDetailActivity.class);
		intent.putExtra("position", position);
		intent.putExtra("emailBean", emailBean);
		intent.putExtra("isRead", isRead);
		startActivityForResult(intent, requestCode);

	}

	/**
	 * 获取待阅邮件列表（ 构建待阅邮件列表Request）
	 * 
	 * @param aUsername
	 * @param currPage
	 * @param isReload
	 */
	protected void buildRequestToBeRead(String aUsername, int currPage,
			boolean isReload) {
		if (isReload) {
//			showProgress();
			initCenterUI(false, mToBeReadListView, mProgressToBeRead);
			mToBeReadPullListView.showHeadView();
		}
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("uid", aUsername));
		
//		params.add(new BasicNameValuePair("CurrPage", currPage + ""));
		params.add(new BasicNameValuePair("flag", 0 + ""));
		params.add(new BasicNameValuePair("pagesize", GlobalVars.pageCount + ""));
		params.add(new BasicNameValuePair("currpage", currPage + ""));
		netRequestToBeRead(new EmailListRequest(params), isReload);
	}

	/**
	 * 获取待阅邮件列表
	 * 
	 * @param request
	 * @param isReload
	 *            true是刷新 false是加载更多
	 */
	private void netRequestToBeRead(AbstractRequest request,
			final boolean isReload) {
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
//				dismisProgress();
				initCenterUI(true, mToBeReadListView, mProgressToBeRead);
				mToBeReadPullListView.onRefreshComplete();
				EmailListRequest toBeReadRequest = (EmailListRequest) request;
				if (toBeReadRequest.emails != null) {
					if (isReload) {
						mIsLoad[0] = true;
						if (toBeReadRequest.emails.size() == 0) {
							mToBeReadEmails.clear();
							mToBeReadAdapter.notifyDataSetChanged();
							EmailActivity.this.showToast("暂无待阅邮件");
							return;
						}
						currentToBeReadPage++;
						mToBeReadEmails.clear();
					} else {
						if (toBeReadRequest.emails.size() == 0) {
							EmailActivity.this.showToast("没有更多待阅邮件");
							return;
						}
						currentToBeReadPage++;
					}
					mToBeReadEmails.addAll(toBeReadRequest.emails);
					mToBeReadAdapter.notifyDataSetChanged();

				}
			}

			@Override
			public void onCancel() {
				if (isReload) {
					mIsLoad[0] = false;
				}
//				dismisProgress();
				initCenterUI(true, mToBeReadListView, mProgressToBeRead);
				mToBeReadPullListView.onRefreshComplete();
			}

			@Override
			public void onProgress(int progress, String msg) {
//				dismisProgress();
				EmailActivity.this.showToast(msg);
			}
		}).execute(request);
	}

	@Override
	public void initUI() {
		
		if(GlobalVars.currentUser == null || StringUtils.isEmpty(GlobalVars.currentUser.loginName)) {
			this.showToast("登录用户过期，请重新登录！");
			Intent intent = new Intent(EmailActivity.this,LoginActivity.class);
			startActivity(intent);
			finish();
			return;
		}
		setContentView(R.layout.ui_email);
		
		initNarView();
		
		mViewList = new ArrayList<View>();
		mViewToBeRead = getLayoutInflater().inflate(
				R.layout.ui_email_tobe_read, null);
		mViewList.add(mViewToBeRead);
		mViewHaveRead = getLayoutInflater().inflate(
				R.layout.ui_email_have_read, null);
		mViewList.add(mViewHaveRead);

		mViewPager = (ViewPager) findViewById(R.id.officialViewpager);

		mAdapter = new ViewPagerAdapter(getApplicationContext(),
				mViewList);
		mViewPager.setAdapter(mAdapter);

		mViewPager.setCurrentItem(0);

		mViewPager
				.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

					public void onPageSelected(int arg0) {
						mGallery.setSelection(arg0);
						handlerHaveRead(arg0);
					}

					public void onPageScrolled(int arg0, float arg1, int arg2) {

					}

					public void onPageScrollStateChanged(int arg0) {

					}
				});

		mGallery = (Gallery) findViewById(R.id.officialGallery);

		String[] gallery_titles = { "待阅邮件", "已阅邮件" };

		List<String> lstGalleryTitle = new ArrayList<String>();
		for (int i = 0; i < gallery_titles.length; i++) {
			lstGalleryTitle.add(gallery_titles[i]);
		}

		mEmailAdapter = new GalleryAdapter(this, lstGalleryTitle);
		mGallery.setAdapter(mEmailAdapter);

		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				mEmailAdapter.notifyDataSetChanged(position);
				mViewPager.setCurrentItem(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		mToBeReadPullListView = (PullToRefreshListView) mViewToBeRead
				.findViewById(R.id.officalListToBeRead);
		mHaveReadPullListView = (PullToRefreshListView) mViewHaveRead
				.findViewById(R.id.officalListHaveRead);
		mToBeReadListView = mToBeReadPullListView.getRefreshableView();
		mHaveReadListView = mHaveReadPullListView.getRefreshableView();
		
//		mToBeReadPullListView.setMode(PullToRefreshListView.MODE_PULL_DOWN_TO_REFRESH);
//		mHaveReadPullListView.setMode(PullToRefreshListView.MODE_PULL_DOWN_TO_REFRESH);
		
		mProgressToBeRead = (ProgressBar) mViewToBeRead.findViewById(R.id.offToBeReadProgress);
		mProgressHaveRead = (ProgressBar) mViewHaveRead.findViewById(R.id.offHaveReadProgress);

	}
	
	
	private void initNarView() {
		narView = (NarView)this.findViewById(R.id.comNarView);
		narView.enterModule(narView.ids[1]);
	}

	protected void handlerHaveRead(int positon) {
		if (mIsLoad[positon]) {
			return;
		}
		if (positon == 0) {
			buildRequestToBeRead(GlobalVars.currentUser.loginName,
					currentToBeReadPage, true);
		} else {
			buildRequestHaveRead(GlobalVars.currentUser.loginName,
					currentHaveReadPage, true);
		}
	}

	/**
	 * 获取已阅邮件列表（构建Request）
	 * 
	 * @param request
	 * @param isReload
	 *            true是刷新 false是加载更多
	 */
	protected void buildRequestHaveRead(String aUsername, int currPage,
			boolean isReload) {
		if (isReload) {
//			showProgress();
			initCenterUI(false, mHaveReadListView, mProgressHaveRead);
			mHaveReadPullListView.showHeadView();
		}
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("uid", aUsername));
//		params.add(new BasicNameValuePair("CurrPage", currPage + ""));
		params.add(new BasicNameValuePair("flag", 1 + ""));
		params.add(new BasicNameValuePair("pagesize", GlobalVars.pageCount + ""));
		params.add(new BasicNameValuePair("currpage", currPage + ""));
//		params.add(new BasicNameValuePair("RowCount", "10"));
		netRequestHaveRead(new EmailListRequest(params), isReload);
	}

	/**
	 * 获取已阅邮件列表
	 * 
	 * @param request
	 * @param isReload
	 *            true是刷新 false是加载更多
	 */
	private void netRequestHaveRead(AbstractRequest request,
			final boolean isReload) {
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
//				dismisProgress();
				initCenterUI(true, mHaveReadListView, mProgressHaveRead);
				mHaveReadPullListView.onRefreshComplete();
				EmailListRequest haveReadRequest = (EmailListRequest) request;
				if (haveReadRequest.emails != null) {
					if (isReload) {
						mIsLoad[1] = true;
						if (haveReadRequest.emails.size() == 0) {
							mHaveReadEmails.clear();
							mHaveReadAdapter.notifyDataSetChanged();
							EmailActivity.this.showToast("暂无已阅邮件");
							return;
						}
						currentHaveReadPage++;
						mHaveReadEmails.clear();
					} else {
						if (haveReadRequest.emails.size() == 0) {
							EmailActivity.this.showToast("没有更多已阅邮件");
							return;
						}
						currentHaveReadPage++;
					}
					mHaveReadEmails.addAll(haveReadRequest.emails);
					mHaveReadAdapter.notifyDataSetChanged();

				}
			}

			@Override
			public void onCancel() {
				if (isReload) {
					mIsLoad[1] = false;
				}
//				dismisProgress();
				initCenterUI(true, mHaveReadListView, mProgressHaveRead);
				mHaveReadPullListView.onRefreshComplete();
			}

			@Override
			public void onProgress(int progress, String msg) {
//				dismisProgress();
				EmailActivity.this.showToast(msg);
			}
		}).execute(request);
	}

//	/**
//	 * 获取是否是会议（构建是否是会议Request）
//	 * 
//	 * @param request
//	 */
//	public void buildRequestMeeting(String ID, String RID,
//			String issuedOrIsupdateType, boolean issuedOrIsupdate,
//			String readType, final int requestCode) {
//		showProgress();
//		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
//		params.add(new BasicNameValuePair("ID", ID));
//		params.add(new BasicNameValuePair("RID", RID));
//		netRequestMeeting(new OffDocDetailMeetingRequest(params), ID, RID,
//				issuedOrIsupdateType, issuedOrIsupdate, readType, requestCode);
//	}
//
//	/**
//	 * 获取是否是会议
//	 * 
//	 * @param request
//	 */
//	private void netRequestMeeting(AbstractRequest request, final String ID,
//			final String RID, final String issuedOrIsupdateType,
//			final boolean issuedOrIsupdate, final String readType,
//			final int requestCode) {
//		new WcfAsyncTask(this, new OnUICallback() {
//
//			private boolean isMeeting = false;
//
//			@Override
//			public void onGetResult(AbstractRequest request) {
//				dismisProgress();
//				OffDocDetailMeetingRequest meetingRequest = (OffDocDetailMeetingRequest) request;
//
//				if (meetingRequest.success == null
//						|| "".equals(meetingRequest.success)) {
//					EmailActivity.this.showToast("获取会议失败，请稍后再试");
//					return;
//				}
//
//				if (!meetingRequest.success.equals("0")) {
//					isMeeting = true;
//				}
//
//				startActivity(ID, RID, readType, issuedOrIsupdateType,
//						issuedOrIsupdate, isMeeting, requestCode);
//			}
//
//			@Override
//			public void onCancel() {
//				dismisProgress();
//			}
//
//			@Override
//			public void onProgress(int progress, String msg) {
//				dismisProgress();
//				EmailActivity.this.showToast(msg);
//			}
//		}).execute(request);
//	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			
			boolean isHaveReadState = data.getBooleanExtra("isHaveReadState", false);
			if (requestCode == GlobalVars.TO_BE_READ) {
				if(isHaveReadState) {
					mIsLoad[1] = false;
					currentToBeReadPage = 1;
					currentHaveReadPage = 1;
					buildRequestToBeRead(GlobalVars.currentUser.loginName,
							currentToBeReadPage, true);
				}
			} else if (requestCode == GlobalVars.HAVE_READ) {
				
				if(!isHaveReadState) {
					mIsLoad[0] = false;
					currentToBeReadPage = 1;
					currentHaveReadPage = 1;
					buildRequestHaveRead(GlobalVars.currentUser.loginName,
							currentHaveReadPage, true);
				}
				
			}
		}
	}

}
